<?php


namespace app\agent\controller;

use app\admin\model\Personnel;
use app\admin\model\School as modelSchool;
use app\common\model\Area;
use EasyWeChat\Factory;
use app\common\library\Auth;
use think\Db;
use think\Env;

class School extends \app\common\controller\Manage
{
    protected $noNeedLogin = ['config','oauth','login','testlogin'];
    protected $noNeedRight = ['*'];
    protected $app = '';
    protected $appconfig = '';
    protected $ModelSchool;
    protected $ModelPersonnel;
    protected $contollerName = 'School';

    public function _initialize()
    {
        $this->appconfig = $this->config();
        $this->app = Factory::work($this->config());
        $this->auth = Auth::instance();
        $this->model = new modelSchool();
        $this->ModelPersonnel = new Personnel();
        parent::_initialize();
    }

    public function testlogin()
    {
        //访问index 请求授权登录
        $this->auth->IndexLogin('yangliu');
        return $this->redirect('index');
    }

    public function index()
    {
        $where2 = ['province'=>'','city'=>'','area'=>'','type'=>''];
        $areaRow = ['mergename'=>''];
        if($province = $this->request->request('province'))
        {
            $where2['province'] = $province;
        }
        if($city = $this->request->request('city'))
        {
            $where2['city'] = $city;
        }
        if($area = $this->request->request('area'))
        {
            $where2['area'] = $area;
            $areaRow = Area::get($where2['area']);
            $areaRow['mergename'] = str_replace('中国,','',$areaRow['mergename']);
            $areaRow['mergename'] = str_replace(',',' ',$areaRow['mergename']);
        }
        if($type = $this->request->request('type'))
        {
            $where2['type'] = $type;
        }
        if ($this->request->isAjax())
        {
            $this->searchFields = 'name';
            list($where, $sort, $order,$offset, $limit) = $this->buildparams();
            $where2 = array_filter($where2);
            $total = $this->model
                ->where($where)
                ->where($where2)
                ->order('id desc')
                ->count();
            $list = $this->model
                ->where($where)
                ->where($where2)
                ->order('id desc')
                ->paginate($this->request->request('Pagesize',10),false,['query'=>request()->param()]);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        $this->view->assign('where',$where2);
        $this->view->assign('areaRow',$areaRow);
        $this->view->assign('search',$this->request->request('search',''));
        return $this->view->fetch();
    }

    public function add()
    {
        if($this->request->isAjax())
        {
            $schoolArray = $this->request->request('row/a');
            Db::startTrans();
            $school = \app\admin\model\School::create($schoolArray,array_keys($schoolArray));
            if($personnelArray = $this->request->request('teacher/a'))
            {
                foreach ($personnelArray as &$value)
                {
                    $value['school_id'] = $school['id'];
                    unset($value['sex_text']);
                    unset($value['job_text']);
                }
                $personnel = new Personnel();
                $response = $personnel->insertAll($personnelArray);
                if($response == 0)
                {
                    //回滚
                    Db::rollback();
                    $this->success('操作失败');
                }
            }
            //提交
            Db::commit();
            $this->success('添加成功','/agent/school/index');
        }
        return $this->view->fetch();
    }

    public function edit($id = null)
    {
        //获取学校的数据
        if(!$school = $this->model->get($id))
        {
            $this->error('学校不存在！');
        }
        //获取学校的人员
        $personnel = $this->ModelPersonnel->where('school_id','=',$school['id'])->select();
        $this->view->assign('personnel',$personnel);
        $this->view->assign('school',$school);
        return $this->view->fetch();
    }

    public function update()
    {
        if($this->request->isAjax())
        {
            //获取学校的数据
            $schoolData = $this->request->request('row/a');
            $personnelAddData = $this->request->request('add/a');
            $personnelUpdateData = $this->request->request('update/a');
            $personnelDelData = $this->request->request('ids/a');//删除学校的人员 条件 学校id  要删除的id
            $schoolRes = $this->model->isUpdate(true)->save($schoolData);//更新学校数据
            if($personnelUpdateData)
            {
                $updateRes = $this->ModelPersonnel->isUpdate()->saveAll($personnelUpdateData);//更新学校人员数据
            }
            if($personnelAddData)
            {
                foreach ($personnelAddData as &$value)
                {
                    $value['school_id'] = $schoolData['id'];
                }
                $addRes = $this->ModelPersonnel->insertAll($personnelAddData);//添加学校人员数据
            }
            $where['school_id'] = $schoolData['id'];
            $where['id'] = ['in',$personnelDelData];
            $delRes = $this->ModelPersonnel->where($where)->delete();
        }
        $this->success('保存成功！');
    }

    private  function config()
    {
        $config = [
            'agent_id' => Env::get('school.agent_id'),
            'corp_id' => Env::get('user.corp_id'),
            'secret'   => Env::get('school.secret'),
            'response_type' => Env::get('school.response_type'),
            'log' => [
                'level' => Env::get('school.level'),
                'file' => __DIR__.Env::get('school.file'),
            ],
            'oauth'=> [
                'scopes'=> Env::get('school.scopes'),
                'callback' => Env::get('school.callback')
            ]
        ];
        return $config;
    }

    public function oauth()
    {
        $token = $this->app->access_token->getToken();//获取企业微信token
        $code = $this->request->request('code');
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}";
        $user = \fast\Http::get($url);
        if(!empty($user)) $user = json_decode($user,true);
        if($user['errcode'] == 0){
            if(isset($user['UserId'])){
                if(!$this->auth->IndexLogin($user['UserId'])){
                    $this->error(__('您的账户不存在，请联系管理员'));
                }else{
                    return redirect('/agent/school/index');
                }
            }
        }else{
            return redirect($this->request->domain().'/agent/school/index');
        }
    }

    public function login()
    {
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appconfig['corp_id']."&redirect_uri=".$this->appconfig['oauth']['callback']."&response_type=code&scope=".$this->appconfig['oauth']['scopes']."&agentid=".$this->appconfig['agent_id']."&state=1#wechat_redirect";
        return redirect($url);
    }

}